<template>
  <div class="table-all">
    <!-- 搜索区 -->
    <div class="app-container search-box">
      <SearchForm
        :form="searchData.form"
        :options="searchData.options"
        @searchUpdate="search"
        @resetSearchData="resetSearchData"
      ></SearchForm>
    </div>
    <!-- 按钮区 -->
    <div class="app-container table-box">
      <div class="table-main">
        <!-- 表格 -->
        <v-table
          title="事故案例数据"
          v-if="tableMainHeight>0"
          :table-columns="tableColumns"
          :table-data="tableData"
          :loading="loading"
          :is-index="true"
          ref="table"
          :maxHeight="tableMainHeight">
          <template #topButtonList>
            <ButtonForm :buttonList="buttonList" @clickButton="clickButton"></ButtonForm>
          </template>
          <template #largeType="scope">
            {{getLargeTypeLabel(scope.row.largeType)}}
          </template>
          <template #type="scope">
            {{getTypeLabel(scope.row.type)}}
          </template>
          <template #level="scope">
            {{getDictValue(scope.row.level, levelOptions)}}
          </template>
          <template #isSetCase="scope">
            {{ getIsSetCase(scope.row.isSetCase) }}
          </template>
          <template #examineResult="scope">
            {{scope.row.examineResult ? getDictValue(scope.row.examineResult, examineResultOptions) :'未审核'}}
          </template>
          <template #operation="scope">
            <a  v-if="scope.row.examineResult==1"
                v-hasPermission="['riskAccidentCases:update']" class="table-btn-view table-operation"
                @click="handleEdit(scope.row,true)">{{$t('table.approve')}}</a>
            <a v-hasPermission="['riskAccidentCases:list']" class="table-btn-view table-operation"
               @click="handleDetail(scope.row)">{{$t('table.view')}}</a>
            <!--<a v-hasPermission="['riskAccidentCases:delete']" class="table-btn-delete table-operation"-->
            <!--@click="singleDelete(scope.row)">{{$t('table.delete')}}</a>-->
          </template>
        </v-table>
      </div>
      <div class="table-page">
        <!-- 页码 -->
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                    @pagination="search"/>
      </div>
    </div>
    <!-- 详情 -->
    <detailDialog :dialog-visible="detailDialogShow"
                  @success="editSuccess"
                  @close="editClose"
                  :openType="detailOpenType"
                  :id="detailId"
                  :title="detailTitle"
                  :isExamine="isExamine"
    ></detailDialog>
  </div>
</template>

<script>
  import { riskAccidentCasesPage,
    riskAccidentCasesExport,
    riskAccidentCasesDelete } from '@/api/risk/accidentCases'
  import SearchForm from '@/components/searchForm/index'
  import ButtonForm from '@/components/ButtonForm/index'
  import VTable from '@/components/VTable/index'
  import Pagination from '@/components/Pagination/index'
  import detailDialog from './detail.vue'
  export default {
    components:{
      VTable,Pagination,detailDialog,SearchForm,ButtonForm
    },
    data(){
      return{
        tableColumns:[
          {
            prop: 'name',
            label: '事故案例名称',
            minWidth: '150',
            slotname: 'name',
            options: {}
          },
          {
            prop: 'largeType',
            label: '事故大类',
            minWidth: '150',
            slotname: 'largeType',
            options: {}
          },
          {
            prop: 'type',
            label: '事故细类',
            minWidth: '150',
            slotname: 'type',
            options: {}
          },
          {
            prop: 'level',
            label: '级别',
            minWidth: '150',
            slotname: 'level',
            options: {}
          },
          {
            prop: 'occurTime',
            label: '事发时间',
            minWidth: '150',
            slotname: 'occurTime',
            options: {}
          },
          {
            prop: 'occurAddr',
            label: '事发地点',
            minWidth: '150',
            slotname: 'occurAddr',
            options: {}
          },
          {
            prop: 'areaCode',
            label: '事件行政区划',
            minWidth: '150',
            slotname: 'areaCode',
            options: {}
          },
          {
            prop: 'eventSummary',
            label: '事件摘要',
            minWidth: '150',
            slotname: 'eventSummary',
            options: {}
          },
          {
            prop: 'deadNum',
            label: '死亡人数',
            minWidth: '150',
            slotname: 'deadNum',
            options: {}
          },
          {
            prop: 'injuredNum',
            label: '受伤人数',
            minWidth: '150',
            slotname: 'injuredNum',
            options: {}
          },
          {
            prop: 'missingNum',
            label: '失踪人数',
            minWidth: '150',
            slotname: 'missingNum',
            options: {}
          },
          {
            prop: 'directLosses',
            label: '直接经济损失(万元)',
            minWidth: '150',
            slotname: 'directLosses',
            options: {}
          },
          {
            prop: 'responseUnit',
            label: '责任单位',
            minWidth: '150',
            slotname: 'responseUnit',
            options: {}
          },
          // {
          //   prop: 'isSetCase',
          //   label: '是否设置为案例',
          //   minWidth: '150',
          //   slotname: 'isSetCase',
          //   options: {}
          // },
          {
            prop: 'examineResult',
            label: '审核状态',
            minWidth: '150',
            slotname: 'examineResult',
            options: {}
          },
          {
            prop: 'operation',
            label: '操作',
            width: '200',
            align: 'center',
            slotname: 'operation',
            overflow: false,
            fixed: 'right'
          }
        ],
        tableData:[],
        selection: [],
        loading:false,
        total:1,
        pageNum:1,
        pageSize:10,
        detailOpenType:"add",
        detailDialogShow:false,
        detailId:"",
        detailTitle:"新增",
        dict:{},
        searchData:{
          form:{
            name:'',
            type:'',
            level:'',
            occurTimeRange:'',
            areaCodeAll:'',
            provinceCode:"",
            cityCode:"",
            countyCode:"",
            isSetCase:'',
          },
          options:[
            {
              title:'事故案例名称',
              key: "name",
              type: "text",
            },
            {
              title: "分类",
              key: "type",
              type: "cascader",
              option: {
                data: this.typeOptionsFormat,
                props: {
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title:'事故级别',
              key: "level",
              type: "select",
              multiple:false,
              option: {
                data: this.levelOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title:'事发时间',
              key: "occurTimeRange",
              type: "date-to-date",
            },
            {
              title:'事件行政区划',
              key: "areaCodeAll",
              type: "gdAreaSelect",
              changeFn: this.searchAreacodeHandle, //如需对区域数据做更多的处理，可在这里定义方法
            },
            // {
            //   title:'是否案例',
            //   key: "isSetCase",
            //   type: "select",
            //   multiple:false,
            //   option: {
            //     data: [{id:0,label:"否",value:0},{id:1,label:"是",value:1}],
            //     props: {
            //       key: "id", // 指定key对应data的字段
            //       label: "label", // 指定label对应data的字段
            //       value: "value", // 指定value对应data的字段
            //     },
            //   },
            // },
            {
              title:'审核状态',
              key: "examineResult",
              type: "select",
              multiple:false,
              option: {
                data: this.examineResultOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
          ]
        },
        buttonList:[
          // {name:'新增',methods:'handleAdd',type:'primary', hasPremission:["riskAccidentCases:add"]},
          // {name:'导入',methods:'handleImport'},
          {name:'导出数据',methods:'handleExport',type:'primary', hasPremission:["riskAccidentCases:export"]}
        ],
        tableMainHeight: 0,
        // 字典
        typeOptions:[],
        typeOptionsFormat:[],
        levelOptions:[],
        examineResultOptions:[],
        isExamine:false,
      }
    },
    watch: {
      // 字典
      'typeOptions':{
        handler(newVal, oldVal) {
          console.log("newVal=======>",newVal)
          if(newVal){
            this.typeOptionsFormat = newVal.map(t=>{
              let name = JSON.parse(t.name)
              return { label: t.label, value: name.value, children: name.children}
            })
          }
        },
        deep: true,
        immediate: true
      },
      'typeOptionsFormat':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t => {
            if (t.key == 'type') {
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'levelOptions':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t=>{
            if(t.key=='level'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'examineResultOptions':{
        handler(newVal, oldVal) {
          this.searchData.options.forEach(t=>{
            if(t.key=='examineResult'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      }
    },
    methods:{
      getLargeTypeLabel(largeType){
        if(largeType){
          let item  = this.typeOptionsFormat.find(t=>t.value == largeType)
          if(item!=undefined){
            return item.label
          }
          return ''
        }
      },
      getTypeLabel(smallType){
        if(smallType){
          let type = smallType.split(",")
          let item  = this.typeOptionsFormat.find(t=>t.value == type[0])
          if(type.length ==2){
            let type1 = item.children.find(t=> t.value == type[1])
            if(type1!=undefined){
              return type1.label
            }
          }
          if(type.length==3){
            let type1 = item.children.find(t=> t.value == type[1])
            if(type1!=undefined){
              let t =  type1.children.find(x=> x.value == type[2])
              if(t!=undefined){
                return t.label
              }
            }
          }
        }
      },
      getIsSetCase(val){
        if(val==0 || val==1){
          return val ? '是' : '否'
        }
        return ''
      },
      getCheckBoxValue(value,option){
        if(!value){
          return
        }
        let temp = []
        let data = value.split(",")
        data.forEach(t=>{
          let item = option.find(x=> x.value == t)
          if(item != undefined){
            temp.push(item.label)
          }
        })
        return temp.join(",")
      },
      getDictValue(value,option){
        let item = option.find(t=> t.value == value)
        if(item!=undefined){
          return item.label
        }
        return value
      },
      editClose(){
        this.detailDialogShow = false
      },
      editSuccess(){
        this.search()
        this.detailDialogShow = false
      },
      search(){
        this.fetch({
          ...this.searchData.form,
        })
      },
      fetch(params={}){
        params.pageSize = this.pageSize
        params.pageNum = this.pageNum
        if(params.type){
          params.type = params.type.toString()
        }
        // 查询申请中、申请通过、不通过
        if(!this.searchData.form.examineResult){
          params.examineResult = "1,2,3"
        }
        // 市版本-添加区域信息
        params.areaCode = this.$store.state.account.user.deptIds
        console.log("params.===>",params)
        this.loading = true
        riskAccidentCasesPage(params).then(async res=>{
          if(res.code==200){
            this.total = res.data.total
            let rows = res.data.rows
            for(let item of rows){
              item.areaCode = await this.$commonJs.areaCodeToName(item)
            }
            this.tableData = res.data.rows
          }else{
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        }).finally(final=>{
          this.loading = false
        })
      },
      // 重置搜索条件
      resetSearchData(){
        this.searchData.form = {
          name:'',
          type:'',
          level:'',
          occurTimeRange:'',
          areaCodeAll:'',
          provinceCode:"",
          cityCode:"",
          countyCode:"",
          isSetCase:'',
        }
      },
      searchAreacodeHandle(arr){
        console.log(arr)
        this.searchData.form.provinceCode=arr[0]
        this.searchData.form.cityCode=arr[1]
        this.searchData.form.countyCode=arr[2]
      },
      // 触发按钮区域按钮方法
      clickButton(methods){
        this[methods]()
      },
      handleDetail(row){
        this.detailId = row.id
        this.detailOpenType = "detail"
        this.detailTitle = "详情"
        this.detailDialogShow = true
        this.isExamine = true
      },
      handleAdd(){
        this.detailOpenType = "add"
        this.detailTitle = "新增"
        this.detailDialogShow = true
        this.isExamine = false
      },
      handleEdit(row,isExamine){
        this.detailId = row.id
        this.detailOpenType = "edit"
        this.detailTitle="审核"
        this.detailDialogShow = true
        this.isExamine = isExamine
      },
      handleExport(){
        let params = {
          ...this.searchData.form,
        }
        if(!this.searchData.form.examineResult){
          params.examineResult = "1,2,3"
        }
        riskAccidentCasesExport(params,`事故案例_${new Date().getTime()}.xlsx`);
      },
      handleImport(){
        console.log("等待处理")
      },
      closeDialog(){
        this.detailDialogShow = false
      },

      singleDelete(row){
        this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          this.loading = true
          riskAccidentCasesDelete(row.id).then(res=>{
            if(res.code==200){
              this.$message({
                message: this.$t('tips.deleteSuccess'),
                type: 'success'
              })
              this.search()
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          }).finally(final=>{
            this.loading = false
          })
        })
      }
    },
    activated(){
      this.fetch()
    },
    created(){
      // 获取字典值
      this.typeOptions = []
      this.$commonJs.filterDataDict("riskAccidentCasesType",this.typeOptions)
      this.levelOptions = []
      this.$commonJs.filterDataDict("riskAccidentCasesLevel",this.levelOptions)
      this.examineResultOptions = []
      this.$commonJs.filterDataDict("riskAccidentCasesExamineResult",this.examineResultOptions)
    },
    mounted(){
      this.tableMainHeight = document.getElementsByClassName('table-main')[0].clientHeight - 44 //减去顶部按钮列表的高度
    }
  }
</script>

<style lang="scss" scoped>
  .table-all {
    display: flex;
    flex-direction: column;
    height: 100%;

    .search-box {
      padding-bottom: 6px;
    }

    .table-box {
      padding-top: 10px;
      flex: 1;
      display: flex;
      flex-direction: column;

      .table-main {
        flex: 1;
        overflow: auto;
      }

      .table-page {
        // padding-top: 10 px;
        // padding-bottom: 10 px;
      }

      ::v-deep .pagination-container {
        text-align: right;
      }

    }
  }
</style>
